package core

import (
	"com.go-micro.code/todolist/go-micro-todolist/user/model"
	"com.go-micro.code/todolist/go-micro-todolist/user/services"
	"context"
	"errors"
	"github.com/jinzhu/gorm"
)

type UserService struct {
}

func CreateUser(item model.User) *services.UserModel {
	return &services.UserModel{
		ID:        uint32(item.ID),
		UserName:  item.UserName,
		CreatedAt: item.CreatedAt.Unix(),
		UpdatedAt: item.UpdatedAt.Unix(),
	}
}

func (*UserService) UserRegister(ctx context.Context, req *services.UserRequest, resp *services.UserDetailResponse) error {
	if req.Password != req.PasswordConfirm {
		return errors.New("两次密码输入不一致")
	}
	var count int
	if err := model.DB.Model(&model.User{}).Where("user_name=?", req.UserName).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("用户名已存在")
	}
	user := model.User{
		UserName: req.UserName,
	}
	//密码加密
	if err := user.SetPassword(req.Password); err != nil {
		return err
	}
	err := model.DB.Create(&user).Error
	if err != nil {
		return err
	}
	resp.UserDetail = CreateUser(user)
	return nil

}

func (*UserService) UserLogin(ctx context.Context, req *services.UserRequest, resp *services.UserDetailResponse) error {
	var user model.User
	err := model.DB.Where("user_name=?", req.GetUserName()).First(&user).Error
	if err == gorm.ErrRecordNotFound {
		resp.Code = 400
		return errors.New("用户不存在")
	}
	if err != nil {
		resp.Code = 500
		return err
	}
	if !user.CheckPassword(req.Password) {
		resp.Code = 400
		return errors.New("密码错误")
	}
	resp.UserDetail = CreateUser(user)
	return nil
}
